/**
 * Created by qiang on 2017-03-20 .
 */
var self;
var Initials = $('.initials');
var vm = new Vue({
		el: '#main',
		data: {
			receiveList: [],
			sendList: [],
			friendList: [],
			blackList: [],
			requestCount: 0,
			userInfo: null,
            searchKey: '',
			scrollTop: 0
		},
		mounted: function() {
			self = this;
			common.auth(function() {
				if (sessionStorage.getItem("IsNewUser") != 'T') {
					self.loadList();
					self.getUserDetail();
				} else {
					weui.alert("请先完成注册", function() {
						location.href = 'userInfo.html';
					})
				}
			});

            if (Initials.find('li').length < 10) {
                Initials.find('ul').append('<li>A</li><li>B</li><li>C</li><li>D</li><li>E</li><li>F</li><li>G</li><li>H</li><li>I</li><li>J</li><li>K</li><li>L</li><li>M</li><li>N</li><li>O</li><li>P</li><li>Q</li><li>R</li><li>S</li><li>T</li><li>U</li><li>V</li><li>W</li><li>X</li><li>Y</li><li>Z</li><li>#</li><li><img src="../../img/icon-black.png"></li>');
            }

            var windowHeight = $(window).height();
            var InitHeight = windowHeight - 45;
            Initials.height(InitHeight);
            var LiHeight = InitHeight / 30;
            Initials.find('li').height(LiHeight);
            common.YMCount();
		},
		methods: {
            scrollList: function (event) {
                // console.log(event.target.scrollTop);
				self.scrollTop = event.target.scrollTop;
            },
            previewImg: function (url) {
                var imgUrl = url.indexOf('http') < 0 ? window.location.origin + url : url;
                wx.previewImage({
                    current: imgUrl, // 当前显示图片的http链接
                    urls: [imgUrl] // 需要预览的图片http链接列表
                });
            },
			formatNum: function (num) {
				return parseInt(num)
			},
			createChat: function (item, BeBlack) {
                sessionStorage.setItem("FScrollTop", self.scrollTop);
				location.href = 'message.html?openid=' + item.openid + '&chatNo=' + (item.UserNo > self.userInfo.UserNo ? self.userInfo.UserNo + '' + item.UserNo : item.UserNo + '' + self.userInfo.UserNo) + '&userName=' + item.NickName + '&IsBlack=' + item.IsBlack + '&BeBlack=' + (BeBlack || null)
			},
            getWXConfig: function () {
                var getWXConfigCallBack = function (data) {
                    wx.config({
                        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                        appId: data.appId, // 必填，公众号的唯一标识
                        timestamp: parseInt(data.timeStamp), // 必填，生成签名的时间戳
                        nonceStr: data.nonceStr, // 必填，生成签名的随机串
                        signature: data.signature,// 必填，签名，见附录1
                        jsApiList: ['previewImage'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                    });
                }
                service.getWXConfig({url: window.location.href}, getWXConfigCallBack)
            },
			getUserDetail: function () {
				service.getUserDetail({}, function(data) {
					console.log(data)
					if (data && data.userInfo)  {
						self.userInfo = data.userInfo;
					}
				})
			},
			loadList: function () {
				self.getFriendList();
				self.getBlackList();
				self.getMakeFriendList("receive");
				self.getMakeFriendList("send");
			},
			getFriendList: function (callback) {
				var getFriendListCallBack = function(res) {
					console.log(res);
                    for (var i = 0; i < res.length; i++) {
                        res[i].cityAttr = common.getCity(res[i].Province)[parseInt(res[i].City)];
                        res[i].age = new Date().getFullYear() - parseInt(res[i].Birthday.substr(0, 4)) + 1;
                        res[i].constellation = common.getAstro(new Date(res[i].Birthday).getMonth() + 1, new Date(res[i].Birthday).getDate());
                    }
					self.friendList = res;
					self.$nextTick(function() {
						common.lazyLoadImg();
						self.requestCount++;
						if (typeof callback == "function") {
							callback();
						}
					})
				}
				service.getFriendList({ SelectValue: self.searchKey }, getFriendListCallBack);
			},
			getBlackList: function () {
				var getBlackListCallBack = function(res) {
					console.log(res, 'blackList');

                    for (var i = 0; i < res.length; i++) {
                        if (res[i].Province && res[i].City) {
                            res[i].cityAttr = common.getCity(res[i].Province)[parseInt(res[i].City)];
                        }
                        if (res[i].Birthday) {
                            res[i].age = new Date().getFullYear() - parseInt(res[i].Birthday.substr(0, 4)) + 1;
                            res[i].constellation = common.getAstro(new Date(res[i].Birthday).getMonth() + 1, new Date(res[i].Birthday).getDate());
                        }
                        // res[i].cityAttr = common.getCity(res[i].Province)[parseInt(res[i].City)];
                        // res[i].age = new Date().getFullYear() - parseInt(res[i].Birthday.substr(0, 4)) + 1;
                        // res[i].constellation = common.getAstro(new Date(res[i].Birthday).getMonth() + 1, new Date(res[i].Birthday).getDate());
                    }
					self.blackList = res;
					self.$nextTick(function() {
						common.lazyLoadImg();
						self.requestCount++;
					})
				}
				service.getBlackList({}, getBlackListCallBack);
			},
			refreshMakeFriend: function (item) {
				var refreshMakeFriendCallBack = function(res) {
					// self.getMakeFriendList("send");
					weui.toast("再加成功", {duration: 300});
					self.$nextTick(function() {
						common.lazyLoadImg();
						self.requestCount++;
					})
				}
				var options = {
                    "AddId": item.AddId,
                    "TaOpenId": item.openid
				};
				service.refreshMakeFriend(options, refreshMakeFriendCallBack);
			},
			getMakeFriendList: function (type) {
				var getMakeFriendListCallBack = function(res) {
					console.log(res);

                    for (var i = 0; i < res.data.length; i++) {
                    	if (res.data[i].Province && res.data[i].City) {
                            res.data[i].cityAttr = common.getCity(res.data[i].Province)[parseInt(res.data[i].City)];
						}
                    	if (res.data[i].Birthday) {
                            res.data[i].age = new Date().getFullYear() - parseInt(res.data[i].Birthday.substr(0, 4)) + 1;
                            res.data[i].constellation = common.getAstro(new Date(res.data[i].Birthday).getMonth() + 1, new Date(res.data[i].Birthday).getDate());
						}
                    }
					if (type == 'receive') {
						self.receiveList = res.data
					} else if (type == 'send') {
						self.sendList = res.data
					}
					self.$nextTick(function() {
						common.lazyLoadImg();
						self.requestCount++;
					})
				}
				var options = {
					ListType: type
				}
				service.getMakeFriendList(options, getMakeFriendListCallBack);
			},
			removeMakeFriend: function (addId) {
				var removeMakeFriendCallBack = function(res) {
					self.getMakeFriendList("send");
					weui.toast("删除成功", {duration: 300});
				};
				var options = {
					"AddId": addId
				};
				service.removeMakeFriend(options, removeMakeFriendCallBack);
			},
            sendAcceptMessage: function (item) {
                var createChatCallBack = function (res) {};
                var options = {
                    ChatNo: (item.UserNo > self.userInfo.UserNo ? self.userInfo.UserNo + '' + item.UserNo : item.UserNo + '' + self.userInfo.UserNo),
                    ToOpenId: item.openid,
                    ChatContent: '我通过了你的朋友验证请求，现在我们可以开始聊天了'
                };
                service.createChat(options, createChatCallBack);
            },
			acceptMakeFriend: function (item) {
				var acceptMakeFriendCallBack = function(res) {
					self.getFriendList();
					self.getMakeFriendList("receive");
					weui.toast("请到聊聊查看新的好友", {duration: 1000});
					self.sendAcceptMessage(item)
				};
				var options = {
					"AddId": item.AddId
				};
				service.acceptMakeFriend(options, acceptMakeFriendCallBack);
			},
			createBlack: function (openId) {
				var createBlackCallBack = function(res) {
					self.getFriendList(self.getBlackList);
					self.getMakeFriendList("receive");
					weui.toast("拉黑成功", {duration: 300});
				};
				var options = {
					"BlackOpenId": openId
				};
				service.createBlack(options, createBlackCallBack);
			},
			deleteBlack: function (blackId) {
				var createBlackCallBack = function(res) {
					self.getFriendList(self.getBlackList);
					weui.toast("你们已经是好友了", {duration: 300});
				};
				var options = {
					"BlackId": blackId
				};
				service.deleteBlack(options, createBlackCallBack);
			},
			addFriend: function (openId) {
				if (self.userInfo.ShareAddNum <= 0) {
//				weui.confirm("可加好友次数不足，你可以：");
					weui.confirm('积分不足，你可以：', {
						buttons: [{
							label: '获得更多积分',
							type: 'primary',
							onClick: function() {

							}
						}, {
							label: '返回',
							type: 'default',
							onClick: function() {

							}
						}]
					});
				} else {
					var addFriendCallBack = function(res) {
						weui.toast("请求发送成功", {duration: 300});
						self.getMakeFriendList("send");
						self.getBlackList();
						self.userInfo.ShareAddNum--;
					};
					var options = {
						"TaOpenId": openId
					};
					service.addFriend(options, addFriendCallBack);
				}
			},
			jumpToMB: function (openId) {
                sessionStorage.setItem("FScrollTop", self.scrollTop);
				location.href = 'message_board.html?openid=' + openId
			},
			jumpToUserDetail: function (openId, IsBlack) {
				if (IsBlack === 'T' || (IsBlack && IsBlack !== 'F')) {
                    weui.alert("ta已拉黑你，无法查看");
				} else {
                    sessionStorage.setItem("FScrollTop", self.scrollTop);
					location.href = 'userInfo.html?toOpenId=' + openId
				}
                // location.href = 'userInfo.html?toOpenId=' + openId
			}
		},
		watch: {
			requestCount: function (val) {
				if (val >= 4) {
					var LetterBox = $('#letter');

                    initials();

					$(".initials ul li").off("click").on("click", function () {
						var _self = $(this);
						var LetterHtml = _self.html();
						LetterBox.html(LetterHtml).fadeIn();

						Initials.css('background', 'rgba(145,145,145,0.6)');

						setTimeout(function () {
							Initials.css('background', 'rgba(145,145,145,0)');
							LetterBox.fadeOut();
						}, 1000);

						var _index = _self.index()
						switch (_index) {
							case 0:
								$('.user-list').animate({scrollTop: '0px'}, 300);
								break;
							case 1:
								var LetterTop = $('#holdHim').position().top;
								$('.user-list').animate({scrollTop: LetterTop - 90 + 'px'}, 300);
								break;
							case 28:
								var LetterTop = $('#default').position().top;
								$('.user-list').animate({scrollTop: LetterTop + 'px'}, 300);
								break;
							case 29:
								var DefaultTop = $('#black').position().top;
								$('.user-list').animate({scrollTop: DefaultTop + 'px'}, 300);//点击最后一个滚到黑名单
								break;
							default:
								var LetterTop = $('#' + _self.text()).position().top;
								$('.user-list').animate({scrollTop: LetterTop - 90 + 'px'}, 300);
								break;
						}
					})

					self.$nextTick(function () {
						if (sessionStorage.getItem('FScrollTop')) {
                            document.querySelector(".user-list").scrollTop = sessionStorage.getItem('FScrollTop');
                            sessionStorage.removeItem('FScrollTop')
						}
                    })
					$(".loading-bg").hide();
				}
			}
		}
	})

var SortList;
var SortBox;
function initials() {//排序
	SortList = $(".user-list .user-item");
	SortBox = $(".user-list");
	SortBox.html('')
	SortList.sort(asc_sort).appendTo('.user-list');//按首字母排序
	function asc_sort(a, b) {
		return makePy($(b).find('.username').text().charAt(0))[0].toUpperCase() < makePy($(a).find('.username').text().charAt(0))[0].toUpperCase() ? 1 : -1;
	}
	insertForItemAfter(SortList);
}

var insertForItemAfter = function () {
	var initials = ["等我通过", "等ta通过"];
	var num = 0;
	SortList.each(function (i) {
		var initial = makePy($(this).find('.friends .username').text().charAt(0))[0].toUpperCase();
		if (initial >= 'A' && initial <= 'Z') {
			if (initials.indexOf(initial) === -1)
				initials.push(initial);
		} else {
            if (initials.indexOf('#') === -1)
                initials.push('#');
			num++;
		}
	});
//	initials.push("#");
	$.each(initials, function (index, value) {//添加首字母标签
		if (value === '等我通过') {
            SortBox.append('<div class="sort_letter hairline-bottom" id="holdMe">' + value + '</div>');
		} else if (value === '等ta通过') {
            SortBox.append('<div class="sort_letter hairline-bottom" id="holdHim">' + value + '</div>');
		} else if (value !== "#") {
			SortBox.append('<div class="sort_letter hairline-bottom" id="' + value + '">' + value + '</div>');
		}
	});

	if (initials.indexOf('#') >= 0) {
        SortBox.append('<div class="sort_letter hairline-bottom" id="default">#</div>');
	}

    SortBox.append('<div class="sort_letter hairline-bottom" id="black">黑名单</div>');

	for (var i = 0; i < SortList.length; i++) {//插入到对应的首字母后面
		var upperCaseVal = makePy(SortList.eq(i).find('.username').text().charAt(0))[0].toUpperCase();
		var letter = "";
		if (SortList.eq(i).find(".hold-me").length > 0) {
			letter = "holdMe";
		} else if (SortList.eq(i).find(".hold-him").length > 0) {
			letter = "holdHim";
		} else  if (SortList.eq(i).find(".blacklist").length > 0) {
			letter = "black";
		} else if (upperCaseVal >= 'A' && upperCaseVal <= 'Z') {
			letter = upperCaseVal;
		} else {
            letter = 'default';
		}
		var dom = SortList.eq(i);
        $('#' + letter).after(dom);
	}
}